I'm working with a Laravel 5.2 application. In my development and staging environments, I'd like to make use of the "Universal To" mail config option described in the docs. A universal to in development environments ensures all emails go to that address, instead of out to real customers/clients/whatever.
I can't work out how to specify this differently in production though. In production there should be no universal to - emails should go out to real addresses.
The standard approach of using different env() values does not seem to work. For example:
config/mail.php:
'to' => [
'address' => env('UNIVERSAL_TO', false)
],
development .env:
UNIVERSAL_TO=my-testing-address@somewhere.com
This works fine - all emails go to the specified UNIVERSAL_TO, as expected. But if I change that to what I will want in production, eg:
production .env
UNIVERSAL_TO=
(or ='', or =false, or simply omitting this completely), sending any mail fails with (in storage/laravel.log):
local.ERROR: exception 'Swift_RfcComplianceException' with message 'Address in mailbox given [] does not comply with RFC 2822, 3.6.2.' in path/to/vendor/swiftmailer/swiftmailer/lib/classes/Swift/Mime/Headers/MailboxHeader.php:348
config/mail.php is just returning an array, so I suppose I could instead set it as a variable and then depending on environment append the 'to' to it, like so:
$return = [ ... normal mail config array ... ];
if (!\App::environment('production')) {
$return['to'] => [
'address' => 'my-testing-address@somewhere.com'
];
}
return $return;
But this seems a little ... hacky. Is there a better way?
I think this should work - it leaves config('mail.to') as null unless UNIVERSAL_TO is set.
'to' => env('UNIVERSAL_TO', false) ? [
'address' => env('UNIVERSAL_TO'),
'name' => env('UNIVERSAL_TO_NAME')
] : null,
I stumbled on this issue when googling for this behaviour. Since the answers aren't perfect, I decided to add my results.
If it ever was broken, it seems this has been fixed now. When omitting the UNIVERSAL_TO in your .env file, the Mail will just be sent to the designated recipient.
Perhaps the issue was that you didn't have a null value, but false as default.
config/mail.php
'to' => [
'address' => env('MAIL_GLOBAL_RECIPIENT'), // when not found, defaults to null
'name' => 'Developer'
],
local .env
MAIL_GLOBAL_RECIPIENT=my@email.com
production .env doesn't even have that variable
Yes I still do pretty much what you call as hacky way and for now I still haven't found any better ways.
$default = [
....
]
if (env('APP_ENV', 'local') === 'staging'){
$default['to'] = [
'address' => 'webmaster@xxx.com',
]
}
return $default;